#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <optional>

// 6.10: 阻塞等待互斥锁（条件变量，等待队列）
class SleepMutex {
public:
    SleepMutex() : locked(false) {}

    void lock() {
        std::unique_lock<std::mutex> lk(internal);
        cv.wait(lk, [&]{ return !locked; });
        locked = true;
    }

    void unlock() {
        {
            std::lock_guard<std::mutex> lk(internal);
            locked = false;
        }
        cv.notify_one();
    }

private:
    bool locked;
    std::mutex internal;
    std::condition_variable cv;
};

int main() {
    SleepMutex mtx;
    int shared = 0;
    const int threads = 4;
    const int iterations = 50000;

    std::vector<std::thread> workers;
    workers.reserve(threads);
    for (int i = 0; i < threads; ++i) {
        workers.emplace_back([&]() {
            for (int k = 0; k < iterations; ++k) {
                mtx.lock();
                ++shared;
                mtx.unlock();
            }
        });
    }
    for (auto& t : workers) t.join();
    std::cout << "SleepMutex shared: " << shared << std::endl;
    return 0;
}